/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fileidentifier.gifutil;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 *
 * @author ApT
 */
public class GifUtil {

    public static final List<String> TEMPLATE_HEADER = new ArrayList<String>();

    static {
        TEMPLATE_HEADER.add("GIF89a");
    }
    private File file;
    private DataInputStream inputStream;
    private byte[] dataArray;
    private int width = 0;
    private int height = 0;
    private int countImage = 0;
    private String fileHeader;

    public GifUtil(String filePath) throws FileNotFoundException, IOException {
        file = new File(filePath);
        dataArray = new byte[(int) file.length()];
        inputStream = new DataInputStream(new FileInputStream(file));
        inputStream.readFully(dataArray);
        inputStream.close();

        fileHeader = calculateFileHeader(dataArray);
        if (checkFileFormat()) {
            width = calculateWidth(dataArray);
            height = calculateHeight(dataArray);
            countImage = calculateImageCount(dataArray);
        }

    }

    public int getWidth() {
        return width;
    }

    public int getHeight() {
        return height;
    }

    public int getCountImage() {
        return countImage;
    }

    public boolean checkFileFormat() {
        if (TEMPLATE_HEADER.contains(fileHeader)) {
            return true;
        }
        return false;
    }

    public String compileFileInfo() {
        if (checkFileFormat()) {
            return "GIF File Information:" + "\n\tIdentifier:\t" + fileHeader + "\n\tImage width:\t" + width
                    + "\n\tImage height:\t" + height + "\n\tImages count:\t" + countImage;
        } else {
            return "This is not .GIF format";
        }
    }

    private String calculateFileHeader(byte[] array) {
        return new String(Arrays.copyOfRange(array, 0, 6)).trim();
    }

    private int calculateWidth(byte[] array) {
        return (array[6] & 0xff) | (array[6 + 1] & 0xff) << 8;
    }

    private int calculateHeight(byte[] array) {
        return (array[8] & 0xff) | (array[8 + 1] & 0xff) << 8;
    }

    private int calculateImageCount(byte[] array) {
        int result = 0;
        int blockType = 0;

        for (int i = 0; i < array.length; i++) {
            blockType = array[i];
            if (blockType == 0x2c) {
                result++;
            }
            if (blockType == 0x3b) {
                break;
            }
        }
        return result;
    }
}
